﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceLocations;
using TinaX;
using TinaX.UIKit;

public class AppStartupLua : MonoBehaviour
{
    public static string pathPrefix = "Assets/Lua/";
    private void Start()
    {
        //初始化lua
        LoadLuaResLocation();
    }
    void LoadLuaResLocation()
    {
        Addressables.LoadResourceLocationsAsync(AddressablesConfig.LuaLabel).Completed += OnLoadLuaResLocationFinish;
    }

    List<IResourceLocation> luaLocations;
    void OnLoadLuaResLocationFinish(AsyncOperationHandle<IList<IResourceLocation>> op)
    {

        if (op.Status == AsyncOperationStatus.Failed)
        {
            Debug.Log("Failed to load LoadLuaResLocation, retrying in 1 second...");
            Invoke("LoadLuaResLocation", 1);
            return;
        }

        luaLocations = new List<IResourceLocation>(op.Result);
        LoadLua();

        
        op.Completed -= OnLoadLuaResLocationFinish;

        //这行代码 真的必要吗？(切换场景会自动销毁）
        Addressables.Release(op);
    }

    async void LoadLua()
    {
        Dictionary<string, byte[]> path2bytes = new Dictionary<string, byte[]>();
        for (int i = 0; i < luaLocations.Count; i++)
        {
            var resLocation = luaLocations[i];
            var textAsset = await Addressables.LoadAssetAsync<TextAsset>(resLocation).Task;
            var path = resLocation.PrimaryKey;

            //这里需要用正则表达式， 这样太难看了
            path = path.Replace(@"\", "/").Replace(pathPrefix, "").Replace("/", ".").Replace(GameConfig.LuaExt, "");

            path2bytes[path] = textAsset.bytes;

            //这行代码 真的必要吗？(切换场景会自动销毁）
            Addressables.Release(textAsset);
        }

        //初始化Lua
        LuaMgr.path2bytes = path2bytes;
        var luaMgr = this.gameObject.AddComponent<LuaMgr>();

        InitTinaX();//初始化TinaX

        GameObject.Destroy(this);
    }

    void InitTinaX()
    {
        var core = XCore.New() //实例化Core对象
        .RegisterServiceProvider(new UIKitProvider()) //注册服务提供者： UIKit
        .OnServicesStartException((service, err) =>
        {
           //接收服务们启动的时候的异常报错信息
        });
        //_ = core.RunAsync(); //启动Core
        core.RunAsync(error =>
        {
            if (error != null)
            {
                //xxxxxx
                Debug.LogError("core run error:" + error.Message);
            }
        });
    }
}
